<?php
// +----------------------------------------------------------------------
// | CatchAdmin [Just Like ～ ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~{$year} http://catchadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://github.com/yanwenwu/catch-admin/blob/master/LICENSE.txt )
// +----------------------------------------------------------------------
// | Author: JaguarJack [ njphper@gmail.com ]
// +----------------------------------------------------------------------

namespace catchAdmin\wechatopen;

use catchAdmin\wechatopen\model\Applet;
use catchAdmin\wechatopen\model\Wechatopen as wechatopenModel;
use catcher\ModuleService;
use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Application as MiniProgram;
use EasyWeChat\OfficialAccount\Application as OfficialAccount;
use EasyWeChat\OpenPlatform\Application as OpenPlatform;
use EasyWeChat\OpenPlatform\Application;
use EasyWeChat\Payment\Application as Payment;
use EasyWeChat\Work\Application as Work;
use think\facade\Cache;
use uctoo\ThinkEasyWeChat\CacheBridge;
use think\facade\Log;
use think\facade\Db;
use uctoo\ThinkEasyWeChat\Facade;

class WechatopenService extends ModuleService
{
    public function register()
    {
        parent::register(); // TODO: Change the autogenerated stub

        $this->registerWechatSDK();
    }

    public function loadRouteFrom()
    {
        // TODO: Implement loadRouteFrom() method.
        return __DIR__ . DIRECTORY_SEPARATOR . 'route.php';
    }

    /**
     * WechatSDK注册
     *
     * @time 2021年03月15日
     * @return void
     */
    protected function registerWechatSDK()
    {
       $apps = [
            'official_account' => OfficialAccount::class,
            'work' => Work::class,
            'mini_program' => MiniProgram::class,
            'payment' => Payment::class,
        ];
        $wechat_default = config('wechat.default') ? config('wechat.default') : [];
        $wechatopen = Db::name('wechatopen')->where('status', 1)->find(); //config('wechat.open_platform.default');  //TODO:读取第三方平台信息表中第一条状态为1的数据
        $wechatopenConfig = [
            'app_id'  => $wechatopen['appid'],
            'secret'  => $wechatopen['appsecret'],
            'token'   => $wechatopen['token'],
            'aes_key' => $wechatopen['encodingAesKey'],
            'oauth' => [
                'scopes'  =>['snsapi_login'],
                'callback'  => 'admin/index/wxlogin_callback',
            ]
        ];
        //合并配置文件
        $account_config = array_merge($wechatopenConfig, $wechat_default);
        Cache::set('wechatopen_config',$account_config);            //第三方平台参数加入缓存，后续如需使用可以从缓存获取配置

        $wechatopen_app =  Factory::openPlatform($account_config);
        $wechatopen_app->rebind('cache',app('cache'));
        $this->app->bind(Application::class,$wechatopen_app);

        //Log::write($wechatopen_app,'debug');
        //Log::write($this->app,'debug');
        /*$appletInfos = Applet::where('status',1)->select()->toArray(); //从数据库获取应用帐号信息
        $appids = array_column($appletInfos,'appid');
        $applets = array_combine($appids,$appletInfos);
        Log::write($applets,'debug');
        foreach ($apps as $name => $app) {  //这段算法极烂
            foreach ($applets as $appid => $applet_info) {
                if($applet_info['typedata'] == 'miniapp'){
                    bind('wechat.mini_program.'.$appid, function ($config = [] ) use ($app, $applet_info, $wechat_default) {
                        $config = ['app_id'=>$applet_info['appid'], 'secret' =>$applet_info['appsecret'] , 'token'=> $applet_info['token'], 'aes_key' =>$applet_info['aeskey'], 'wechatapplet_id' =>$applet_info['wechatapplet_id']];
                        //合并配置文件
                        $applet_config = Applet::getAppletConfig($applet_info['appid']);   //TODO::待优化的极烂算法
                        $applet_app = app($app, ['config' => $applet_config]);
                        if ($wechat_default['use_tp_cache']) {
                            $applet_app['cache'] = app(CacheBridge::class);
                        }
                        return $applet_app;
                    });
                }
                if(($applet_info['typedata'] == 'serv_account') || ($applet_info['typedata'] == 'sub_account')){
                    bind('wechat.official_account.'.$appid, function ($config = [] ) use ($app, $applet_info, $wechat_default) {
                        $config = ['app_id'=>$applet_info['appid'], 'secret' =>$applet_info['appsecret'] , 'token'=> $applet_info['token'], 'aes_key' =>$applet_info['aeskey'], 'wechatapplet_id' =>$applet_info['wechatapplet_id']];
                        $applet_config = Applet::getAppletConfig($applet_info['appid']);//array_merge($config,$wechat_default);
                        $applet_app = app($app, ['config' => $applet_config]);
                        if ($wechat_default['use_tp_cache']) {
                            $applet_app['cache'] = app(CacheBridge::class);
                        }
                        return $applet_app;
                    });
                }
                if($applet_info['typedata'] == 'work_account'){
                    bind('wechat.work.'.$appid, function ($config = [] ) use ($app, $applet_info, $wechat_default) {
                        $config = ['app_id'=>$applet_info['appid'], 'secret' =>$applet_info['appsecret'] , 'token'=> $applet_info['token'], 'aes_key' =>$applet_info['aeskey'], 'wechatapplet_id' =>$applet_info['wechatapplet_id']];
                        $applet_config = Applet::getAppletConfig($applet_info['appid']);//array_merge($config,$wechat_default);
                        $applet_app = app($app, ['config' => $applet_config]);
                        if ($wechat_default['use_tp_cache']) {
                            $applet_app['cache'] = app(CacheBridge::class);
                        }
                        return $applet_app;
                    });
                }
            }
            if (isset($applets['default'])) {
                bind('wechat.' . $name, 'wechat.' . $name . '.default');
            }
        }*/

    }
}
